import os
import shutil

# ========================
# 配置部分
# ========================

# 旧项目备份目录
OLD_DIR = "old"

# 新项目目录结构定义
PROJECT_STRUCTURE = {
    "backend": {
        "templates": {},
        "static": {},
        "files": [
            ("app.py", "# Flask 应用入口\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/')\ndef home():\n    return 'Hello, World!'\n"),
            ("models.py", "# 数据库模型定义\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n"),
            ("requirements.txt", "# Python依赖包列表\nflask\nflask-sqlalchemy\nflask-cors\nrequests\nbeautifulsoup4\n")
        ]
    },
    "frontend": {
        "public": {},
        "src": {
            "assets": {},
            "components": {},
            "views": {},
            "files": [
                ("main.ts", "// Vue 应用入口\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport ElementPlus from 'element-plus';\nimport 'element-plus/dist/index.css';\n\nconst app = createApp(App);\napp.use(ElementPlus);\napp.mount('#app');\n"),
                ("App.vue", "<template>\n  <div id=\"app\">\n    <h1>Hello Vue + Element Plus!</h1>\n  </div>\n</template>\n\n<script lang=\"ts\">\nimport { defineComponent } from 'vue';\nexport default defineComponent({\n  name: 'App',\n});\n</script>"),
                ("shims-vue.d.ts", "declare module '*.vue' {\n  import type { DefineComponent } from 'vue';\n  const component: DefineComponent<{}, {}, any>;\n  export default component;\n}")
            ]
        },
        "files": [
            ("package.json", "{\n  \"name\": \"frontend\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"vite build\"\n  },\n  \"dependencies\": {\n    \"element-plus\": \"^2.3.6\",\n    \"vue\": \"^3.4.21\"\n  },\n  \"devDependencies\": {\n    \"@vitejs/plugin-vue\": \"^5.0.4\",\n    \"typescript\": \"^5.3.3\",\n    \"vite\": \"^5.1.6\"\n  }\n}"),
            ("tsconfig.json", "{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"module\": \"esnext\",\n    \"strict\": true,\n    \"jsx\": \"preserve\",\n    \"moduleResolution\": \"node\",\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \".\",\n    \"types\": [\"webpack-env\", \"vite/client\"]\n  },\n  \"include\": [\n    \"src/**/*.{ts,vue,tsx,js}\"\n  ],\n  \"exclude\": [\n    \"node_modules\"\n  ]\n}"),
            ("vite.config.ts", "import { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\nexport default defineConfig({\n  plugins: [vue()],\n  server: {\n    proxy: {\n      '/api': {\n        target: 'http://localhost:5000',\n        changeOrigin: true,\n        rewrite: (path) => path.replace(/^\\/api/, '')\n      }\n    }\n  }\n});")
        ]
    },
    "README.md": "# 我的导航网站后台管理系统\n\n这是基于 Flask + Vue3 + TypeScript + Element Plus 的前后端分离项目。\n\n## 开发步骤\n\n1. 安装前端依赖：`npm install`\n2. 运行前端：`npm run dev`\n3. 启动后端：`python backend/app.py`\n"
}

# ========================
# 工具函数
# ========================

def ensure_dir(path):
    """确保目录存在"""
    os.makedirs(path, exist_ok=True)

def move_existing_files(target_dir):
    """将当前目录下的所有非 Git 文件/文件夹移到 old 目录中"""
    current_files = os.listdir('.')
    for f in current_files:
        if f in [OLD_DIR, "__pycache__", os.path.basename(__file__), ".git", ".gitignore"]:  # 忽略 git 和脚本自身
            continue
        src_path = os.path.join('.', f)
        dst_path = os.path.join(target_dir, f)
        print(f"Moving: {src_path} -> {dst_path}")
        try:
            if os.path.isdir(src_path):
                shutil.move(src_path, dst_path)
            else:
                if not os.path.exists(dst_path):
                    shutil.move(src_path, dst_path)
                else:
                    print(f"Skipped (already exists): {dst_path}")
        except Exception as e:
            print(f"Error moving {f}: {e}")

def create_structure(base_path, structure):
    """递归创建目录结构并生成空文件或带基础模板内容的文件"""
    for name, content in structure.items():
        path = os.path.join(base_path, name)
        if isinstance(content, dict):
            # 是目录
            ensure_dir(path)
            create_structure(path, content)
        elif isinstance(content, list):
            # 是文件列表
            for file_info in content:
                if isinstance(file_info, tuple) and len(file_info) == 2:
                    file_name, file_content = file_info
                    file_path = os.path.join(base_path, file_name)
                    if not os.path.exists(file_path):
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(file_content)
                        print(f"Created file with content: {file_path}")
                    else:
                        print(f"Skipped (already exists): {file_path}")
        elif isinstance(content, str):
            # 是单个文件
            file_path = os.path.join(base_path, name)
            if not os.path.exists(file_path):
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                print(f"Created empty file: {file_path}")

# ========================
# 主程序逻辑
# ========================

if __name__ == "__main__":
    print("开始迁移项目结构...")

    # 1. 创建 old 文件夹并移动现有文件进去
    ensure_dir(OLD_DIR)
    print(f"已创建目录: {OLD_DIR}")
    move_existing_files(OLD_DIR)

    # 2. 创建新项目结构
    print("\n开始创建新项目结构...")
    create_structure(".", PROJECT_STRUCTURE)

    print("\n✅ 项目结构迁移完成！")